package com.yhj.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @author yaohj
 * @Description: 这个也可以通过配置文件直接配置
 * @date 2024年11月21日 14:26
 */
@Configuration
public class RedisConfig {
    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private int port;

    @Value("${spring.redis.password}")
    private String password;

    @Value("${spring.redis.timeout}")
    private int timeout;

    @Bean
    JedisConnectionFactory redisConnectionFactory() {
        // 自定义JedisConnectionFactory配置
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        // 配置连接池参数，比如最大连接数、最大等待时间等
        poolConfig.setMaxTotal(8);
        poolConfig.setMaxIdle(8);
        poolConfig.setMinIdle(0);
        poolConfig.setMaxWaitMillis(10000);
        poolConfig.setTestOnBorrow(true);

        JedisConnectionFactory factory = new JedisConnectionFactory();
        factory.setHostName(host);
        factory.setPort(port);
        factory.setPassword(password);
        factory.setPoolConfig(poolConfig);
        factory.setTimeout(timeout);
        factory.afterPropertiesSet(); // 初始化连接工厂

        return factory;
    }

    @Bean
    public RedisTemplate<Object, Object> redisTemplate() {
        // 使用自定义的JedisConnectionFactory
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory());
        return template;
    }

    @Bean
    public StringRedisTemplate stringRedisTemplate() {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory());
        return template;
    }
}
